package dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import pojo.Book;
import util.DBUtils;
import dao.BookDao;

public class BookDaoImpl extends BaseDaoImpl<Book> implements BookDao {

	@Override
	public int add(Book book) {
		String sql = "insert into books values(?,?,?,?)";
		PreparedStatement pst = null;
		int m = 0;
		Connection conn = DBUtils.createConnection();
		try {
			pst = conn.prepareStatement(sql);
			pst.setString(1, UUID.randomUUID().toString());
			pst.setString(2, book.getBname());
			pst.setString(3, book.getPhoto());
			pst.setDouble(4, book.getPrice());
			m = pst.executeUpdate();
		} catch (SQLException e) {
			logger.error(e);
		}finally{
			DBUtils.close(conn, pst, null);
		}
		return m;
	}

	@Override
	public int delete(String id) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int update(Book t) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public Book load(String id) {
		String sql = "select * from books where id=?";
		Connection conn = DBUtils.createConnection();
		PreparedStatement pst = null;
		ResultSet rs = null;
		Book book =null;
		try {
			pst = conn.prepareStatement(sql);
			pst.setString(1, id);
			rs = pst.executeQuery();
			if (rs.next()) {
				book = new Book();
				book.setId(rs.getString("id"));
				book.setBname(rs.getString("bname"));
				book.setPhoto(rs.getString("photo"));
				book.setPrice(rs.getDouble("price"));
			}
		} catch (Exception e) {
			logger.error(e);
		}finally{
			DBUtils.close(conn, pst, rs);
		}
		return book;	
	}


	@Override
	public List<Book> findAll() {
		String sql = "select * from books";
		Connection conn = DBUtils.createConnection();
		PreparedStatement pst = null;
		ResultSet rs = null;
		List<Book> books = new ArrayList<>(); 
		try {
			pst = conn.prepareStatement(sql);
			rs = pst.executeQuery();
			while(rs.next()) {
				Book book = new Book();
				book.setId(rs.getString("id"));
				book.setBname(rs.getString("bname"));
				book.setPhoto(rs.getString("photo"));
				book.setPrice(rs.getDouble("price"));
				books.add(book);
			}
		} catch (Exception e) {
			logger.error(e);
		}finally{
			DBUtils.close(conn, pst, rs);
		}
		return books;	
	}

}
